//
//  AppDelegate.m
//  logistics
//
//  Created by 孔凡列 on 16/3/29.
//  Copyright © 2016年 czebd. All rights reserved.
//

#import "AppDelegate.h"
#import "CZTabBarViewController.h"
#import "CZNewsfeatureController.h"

#import <BaiduMapAPI_Map/BMKMapComponent.h>

#import <AlipaySDK/AlipaySDK.h>

#import "JPUSHService.h"

#import "EaseMob.h"

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>

//腾讯开放平台（对应QQ和QQ空间）SDK头文件
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>

//微信SDK头文件
#import "WXApiManager.h"
#import "WXApi.h"

#import "CZTopUpTableViewController.h"
#import "CZPayViewController.h"

#import "NSString+Hash.h"

#import <BaiduMapAPI_Location/BMKLocationComponent.h>
//抽屉
#import "MMDrawerController.h"
#import "CZLeftViewController.h"

//附近的疯友
#import "CZAddNearFriendController.h"

//测试
#import "CZBaseController.h"
#import "CZFriendViewController.h"
#import "CZTimeLineTableViewController.h"
#import "CZAddGroupController.h"
#import "CZFriendDetailViewController.h"
#import "CZEditAgeViewController.h"
#import "CZHomeTownController.h"
#import "CZEditDataController.h"
#import "CZMyRoleController.h"
#import "CZAddNearFriendController.h"
#import "CZEducationalController.h"
#import "CZAddPhoneFriendController.h"
#import "CZPublishMessageViewController.h"
#import "CZAddFriendSearchController.h"
#import "CZNewFirendResquestController.h"



//两次提示的默认间隔
static const CGFloat kDefaultPlaySoundInterval = 3.0;
static NSString *kMessageType = @"MessageType";
static NSString *kConversationChatter = @"ConversationChatter";
static NSString *kGroupName = @"GroupName";

////蒲公英
//#import <PgySDK/PgyManager.h>
//#import <PgyUpdate/PgyUpdateManager.h>
//
//#define PGY_APPKEY @"e1c6d12c5c0a49902d840b2adb3ecdb7"

@interface AppDelegate ()<BMKGeneralDelegate,IChatManagerDelegate,WXApiDelegate,BMKLocationServiceDelegate>
@property (nonatomic,strong)BMKMapManager *mapManager;

@property (strong, nonatomic) NSDate *lastPlaySoundDate;

// 定位
@property (nonatomic,strong)BMKLocationService *locService;

@property (nonatomic,weak)NSTimer *timer;



@property (nonatomic,weak)NSTimer *memberTimer;


/** 附近的疯友 */
@property (nonatomic, strong) CZAddNearFriendController *nearFriend;

// 当前的位置
@property (nonatomic,assign)CGFloat longitude;
@property (nonatomic,assign)CGFloat latitude;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    //    if ([WXApi handleOpenURL:url delegate:[[CZTopUpTableViewController alloc] init]]) {
    //        return [WXApi handleOpenURL:url delegate:[[CZTopUpTableViewController alloc] init]];
    //    }
    //    else{
    //        return [WXApi handleOpenURL:url delegate:[[CZPayViewController alloc] init]];
    //    }
    return  [WXApi handleOpenURL:url delegate:[[CZTopUpTableViewController alloc] init]] || [WXApi handleOpenURL:url delegate:[[CZPayViewController alloc] init]];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    
    //    if ([WXApi handleOpenURL:url delegate:[[CZTopUpTableViewController alloc] init]]) {
    //        return [WXApi handleOpenURL:url delegate:[[CZTopUpTableViewController alloc] init]];
    //    }
    //    else{
    //        return [WXApi handleOpenURL:url delegate:[[CZPayViewController alloc] init]];
    //    }
    return [WXApi handleOpenURL:url delegate:[[CZTopUpTableViewController alloc] init]] || [WXApi handleOpenURL:url delegate:[[CZPayViewController alloc] init]];
}
- (BOOL)application:(UIApplication *)application openURL:(nonnull NSURL *)url options:(nonnull NSDictionary<NSString *,id> *)options
{
    // 支付宝
    //    if([[NSString stringWithFormat:@"%@",url] rangeOfString:[NSString stringWithFormat:@"%@://pay",@"2016042601337678"]].location != NSNotFound){
    //        //        CZLog(@"url = %@",url);
    //        [[AlipaySDK defaultService]
    //         processOrderWithPaymentResult:url
    //         standbyCallback:^(NSDictionary *resultDic) {
    ////             CZLog(@"result = %@",resultDic);//返回的支付结果 //【由于在跳转支付宝客户端支付的过程中,商户 app 在后台很可能被系统 kill 了,所以 pay 接 口的 callback 就会失效,请商户对 standbyCallback 返回的回调结果进行处理,就是在这个方法 里面处理跟 callback 一样的逻辑】
    //         }];
    //这里判断是否发起的请求为微信支付，如果是的话，用WXApi的方法调起微信客户端的支付页面（://pay 之前的那串字符串就是你的APPID，）
    // 微信
    if ([[NSString stringWithFormat:@"%@",url] rangeOfString:[NSString stringWithFormat:@"%@://pay",@"wxc8cec7ba28526e82"]].location != NSNotFound) {
        NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"WXPAY"];
        if ([str isEqualToString:@"topup"]) {
            return [WXApi handleOpenURL:url delegate:[[CZTopUpTableViewController alloc] init]];
        }
        else if([str isEqualToString:@"pay"]){
            return [WXApi handleOpenURL:url delegate:[[CZPayViewController alloc] init]];
        }
        //        return  [WXApi handleOpenURL:url delegate:[[CZTopUpTableViewController alloc] init]] || [WXApi handleOpenURL:url delegate:[[CZPayViewController alloc] init]];
    }
    //如果极简开发包不可用，会跳转支付宝钱包进行支付，需要将支付宝钱包的支付结果回传给开发包
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
            CZLog(@"result = %@",resultDic);
        }];
    }
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回authCode
        
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
            CZLog(@"result = %@",resultDic);
        }];
    }
    return YES;
}

#pragma mark - 判断是否登录
// 1.初始化左视图
//UITableViewController * SV;
//// 1.1判断是否登录
//if ([MYUserAccount sharedUserAccount].isLogin) {
//    
//    SV = [[CZBaseController alloc]init];
//}
//else{
//    SV = [[MYDrawerLoginController alloc]init];
//}

#pragma mark - 包装左侧控制器

//// 1.初始化左视图
- (void)swithMaincontroller{
    
//UIViewController * SV = [[CZBaseController alloc]init];
MMDrawerController *drawerController = [[MMDrawerController alloc] initWithCenterViewController:[[CZTabBarViewController alloc]init] leftDrawerViewController:[[CZLeftViewController alloc]init]];

// 3.设置抽屉抽出的宽度
 drawerController.maximumLeftDrawerWidth = 300;
// 4.添加手势
//[drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
//[drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
    
    self.window.rootViewController = drawerController;    
    // 设置启动
    [self.window makeKeyAndVisible];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] init];
    
    // --状态栏颜色  UIStatusBarStyleDefault黑色、UIStatusBarStyleLightContent白色
//    [[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleLightContent  animated:NO];
    
    //蒲公英

    //  关闭用户手势反馈，默认为开启。
    //      [[PgyManager sharedPgyManager] setEnableFeedback:NO];
    
    //  设置用户反馈激活模式为三指拖动，默认为摇一摇。
    //  [[PgyManager sharedPgyManager] setFeedbackActiveType:kPGYFeedbackActiveTypeThreeFingersPan];
    
    //  设置用户反馈界面的颜色，会影响到Title的背景颜色和录音按钮的边框颜色，默认为0x37C5A1(绿色)。
    //  [[PgyManager sharedPgyManager] setThemeColor:[UIColor blackColor]];
    
    //  设置摇一摇灵敏度，数字越小，灵敏度越高，默认为2.3。
    //  [[PgyManager sharedPgyManager] setShakingThreshold:3.0];
    //  是否显示蒲公英SDK的Debug Log，如果遇到SDK无法正常工作的情况可以开启此标志以确认原因，默认为关闭。
    //  [[PgyManager sharedPgyManager] setEnableDebugLog:YES];
    
    //  启动SDK
    //  设置三指拖动激活摇一摇需在此调用之前
    //    [[PgyUpdateManager sharedPgyManager] startManagerWithAppId:PGY_APPKEY];
    //    [[PgyManager sharedPgyManager] startManagerWithAppId:PGY_APPKEY];
    // 要使用百度地图，请先启动BaiduMapManager
    self.mapManager = [[BMKMapManager alloc]init];
    BOOL ret = [_mapManager start:@"ek3q3QIHBLB1NODgrNcHAs3kssUeRaUH" generalDelegate:self];
    if (!ret) {
        CZLog(@"manager start failed!");
    }
    
    CZTabBarViewController *tabBarVc = [[CZTabBarViewController alloc] init];
    CZNewsfeatureController *vc = [[CZNewsfeatureController alloc] init];
    tabBarVc.view.backgroundColor = [UIColor whiteColor];
    
    //    0、获得版本对应的key
    NSString *versionKey = (__bridge NSString *)kCFBundleVersionKey;
    //    1、获得上次保存的版本
    NSString *lastVersion = [[NSUserDefaults standardUserDefaults] stringForKey:versionKey];
    //    2、获得当前的版本号
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[versionKey];
    //    3、比较版本是否最新
    if (![currentVersion isEqualToString:lastVersion]) {
        //       新版本－－显示新特性
        //        保存版本号
        [[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:versionKey];
        //       创建NewDfeatureController,并设置窗口的根控制器
        self.window.rootViewController = vc;
        
    }
    else{
        //    旧版本－－显示自定义TabBarController
        //    创建tabbar控制器,并设置为窗口的跟控制器
        self.window.rootViewController = tabBarVc;
        [self swithMaincontroller];
        /**
         *  测试
         */
//        self.window.rootViewController = [[CZAddFriendSearchController alloc]init];
    }
    [self.window makeKeyAndVisible];
    //Required
    //如需兼容旧版本的方式，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化和同时使用pushConfig.plist文件声明appKey等配置内容。
    [JPUSHService setupWithOption:launchOptions appKey:@"0a1f5df94995a9e237aead74"
                          channel:@"App Store"
                 apsForProduction:TRUE
            advertisingIdentifier:nil];
    [[NSUserDefaults standardUserDefaults] setObject:launchOptions forKey:APPDELEGATELAUNCHOPTIONS];
    
    //    [CZNotificationCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    //    [CZNotificationCenter addObserver:self selector:@selector(loginSuccess:) name:kJPFNetworkDidLoginNotification object:nil];
    
    //registerSDKWithAppKey:注册的appKey，详细见下面注释。
    //apnsCertName:推送证书名(不需要加后缀)，详细见下面注释。ymhid-demo#cqhxapp easemob-demo#chatdemoui
    [[EaseMob sharedInstance] registerSDKWithAppKey:@"gzcz-2016#logistics" apnsCertName:@"logistics"];
    
    //iOS8 注册APNS
    //    [self registerRemoteNotification];

    [[EaseMob sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    /**
     *  设置ShareSDK的appKey，如果尚未在ShareSDK官网注册过App，请移步到http://mob.com/login 登录后台进行应用注册
     *  在将生成的AppKey传入到此方法中。
     *  方法中的第二个第三个参数为需要连接社交平台SDK时触发，
     *  在此事件中写入连接代码。第四个参数则为配置本地社交平台时触发，根据返回的平台类型来配置平台信息。
     *  如果您使用的时服务端托管平台信息时，第二、四项参数可以传入nil，第三项参数则根据服务端托管平台来决定要连接的社交SDK。
     */
    [ShareSDK registerApp:@"1364dfa600404"
          activePlatforms:@[
                            @(SSDKPlatformSubTypeWechatSession),
                            @(SSDKPlatformTypeWechat),
                            @(SSDKPlatformSubTypeWechatTimeline),
                            @(SSDKPlatformSubTypeWechatFav),
                            @(SSDKPlatformTypeQQ),
                            @(SSDKPlatformSubTypeQZone)]
                 onImport:^(SSDKPlatformType platformType)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class] delegate:self];
                 break;
             case SSDKPlatformTypeQQ:
                 [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                 break;
             default:
                 break;
         }
     }
          onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
     {
         
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [appInfo SSDKSetupWeChatByAppId:@"wxc8cec7ba28526e82"
                                       appSecret:@"82fccc5ccffd7e4aaf5907b9f36e911e"];
                 break;
             case SSDKPlatformTypeQQ:
                 [appInfo SSDKSetupQQByAppId:@"1105203217"
                                      appKey:@"t3aeIfYGSWzrSud8"
                                    authType:SSDKAuthTypeBoth];
                 break;
                 
             default:
                 break;
         }
     }];
    
    
    //向微信注册
    [WXApi registerApp:@"wxc8cec7ba28526e82" withDescription:@"快疯啦"];
    
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                            UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    }
    
    
    [self registerEaseMobNotification];
    
    
    CZAccountModel *account = [CZMessageManager objectKeyedUnarchiverWithFileName:CZLOGISTICSACCOUNTFILENAME];
    
    if (account.userToken) {
        
        account.HXPass = [[NSString stringWithFormat:@"%@jsfojoiawejfj8^&(",[account.id stringValue]] md5String];
        account.HXPass = [[NSString stringWithFormat:@"%@jsfojoiawejfj8^&(",[account.id stringValue]]  md5String];
        [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:[account.id stringValue] password:account.HXPass completion:^(NSDictionary *loginInfo, EMError *error) {
            //        CZLog(@"%@",error);
            if (!error && loginInfo) {
//                CZLog(@"环信登录成功");
//                CZLog(@"%@",loginInfo);
                
                //获取数据库中数据
                [[EaseMob sharedInstance].chatManager loadDataFromDatabase];
            }
            else{
//                CZLog(@"环信登录失败");
            }
        } onQueue:nil];
        
    }
    
    /** app进程被杀死后，启动app获取推送消息 */
    NSDictionary * userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    
    return YES;
}


// 注册推送
- (void)registerRemoteNotification{
    UIApplication *application = [UIApplication sharedApplication];
    application.applicationIconBadgeNumber = 0;
    
    if([application respondsToSelector:@selector(registerUserNotificationSettings:)])
    {
        UIUserNotificationType notificationTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    
#if !TARGET_IPHONE_SIMULATOR
    //iOS8 注册APNS
    if ([application respondsToSelector:@selector(registerForRemoteNotifications)]) {
        [application registerForRemoteNotifications];
    }else{
        UIRemoteNotificationType notificationTypes = UIRemoteNotificationTypeBadge |
        UIRemoteNotificationTypeSound |
        UIRemoteNotificationTypeAlert;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:notificationTypes];
    }
#endif
}


#pragma mark - registerEaseMobNotification
- (void)registerEaseMobNotification{
    [self unRegisterEaseMobNotification];
    // 将self 添加到SDK回调中，以便本类可以收到SDK回调
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
}

- (void)unRegisterEaseMobNotification{
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
}

- (void)onGetNetworkState:(int)iError
{
    if (0 == iError) {
//        CZLog(@"联网成功");
    }
    else{
        CZLog(@"onGetNetworkState %d",iError);
    }
    
}

- (void)onGetPermissionState:(int)iError
{
    if (0 == iError) {
//        CZLog(@"授权成功");
    }
    else {
        CZLog(@"onGetPermissionState %d",iError);
    }
}


- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    CZLog(@"deviceToken = %@",deviceToken);
    [[EaseMob sharedInstance] application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}


- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    CZLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
    [[EaseMob sharedInstance] application:application didFailToRegisterForRemoteNotificationsWithError:error];
    CZLog(@"注册环信推送----------------------error -- %@",error);
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // Required,For systems with less than or equal to iOS6
    // 取得 APNs 标准信息内容
    //    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    //    NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
    //    NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge数量
    //    NSString *sound = [aps valueForKey:@"sound"]; //播放的声音
    //
    //    // 取得Extras字段内容
    //    NSString *action = [userInfo valueForKey:@"action"]; //服务端中Extras字段，key是自己定义的
    //    NSString *sendTime = [userInfo valueForKey:@"sendTime"]; //服务端中Extras字段，key是自己定义的
    //
    //    // 过滤通知，两小时内才响
    //    NSDateFormatter  *dateformat=[[NSDateFormatter alloc] init];
    //    [dateformat setLocale:[NSLocale localeWithLocaleIdentifier:@"zh_CN"]];
    //    [dateformat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //
    //
    //    NSDate *pushDate = [dateformat dateFromString:sendTime];
    //    NSDate *nowDate = [NSDate date];
    //
    //    NSTimeInterval timeInterval0 = [pushDate timeIntervalSinceNow];
    //    NSTimeInterval timeInterval1 = [nowDate timeIntervalSinceNow];
    //    CZLog(@"timeInterval0 = %.2lf,timeInterval1 = %.2lf",timeInterval0,timeInterval1);
    //    if (-timeInterval0 <= 2 * 60 * 60) {
    //        //下面的两个函数都可以用来播放音效文件，第一个函数伴随有震动效果
    //        AudioServicesPlayAlertSound(1007);
    //        // 发送本地推送，通知首页
    //        [CZNotificationCenter postNotificationName:kJPFNetworkDidReceiveMessageNotification object:userInfo];
    //
    //    }
    // Required
    [JPUSHService handleRemoteNotification:userInfo];
}

//iOS 7 Remote Notification
- (void)application:(UIApplication *)application didReceiveRemoteNotification:  (NSDictionary *)userInfo fetchCompletionHandler:(void (^)   (UIBackgroundFetchResult))completionHandler {
    
    CZLog(@"this is iOS7 Remote Notification");
    // 取得 APNs 标准信息内容
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    //    NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
    //    NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge数量
    //    NSString *sound = [aps valueForKey:@"sound"]; //播放的声音
    
    // 取得Extras字段内容
    NSString *action = [userInfo valueForKey:@"action"]; //服务端中Extras字段，key是自己定义的

    CZLog(@"action = %@",action);
    
    
    NSString *sendTime = [userInfo valueForKey:@"sendTime"]; //服务端中Extras字段，key是自己定义的
    
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
    
    // 过滤通知，两小时内才响
    NSDateFormatter  *dateformat=[[NSDateFormatter alloc] init];
    [dateformat setLocale:[NSLocale localeWithLocaleIdentifier:@"zh_CN"]];
    [dateformat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    
    NSDate *pushDate = [dateformat dateFromString:sendTime];
    NSDate *nowDate = [NSDate date];
    
    NSTimeInterval timeInterval0 = [pushDate timeIntervalSinceNow];
    NSTimeInterval timeInterval1 = [nowDate timeIntervalSinceNow];
    CZLog(@"timeInterval0 = %.2lf,timeInterval1 = %.2lf",timeInterval0,timeInterval1);
    if (-timeInterval0 <= 2 * 60 * 60) {
        //下面的两个函数都可以用来播放音效文件，第一个函数伴随有震动效果
//        CZAccountModel *account = [CZMessageManager objectKeyedUnarchiverWithFileName:CZLOGISTICSACCOUNTFILENAME];
        AudioServicesPlayAlertSound(1007);
//        if ([account.isCoutier isEqualToString:@"0"]) {
//            AudioServicesPlayAlertSound(1007);
//        }
//        else{
//            if (account.openRemotePush) {
//                AudioServicesPlayAlertSound(1007);
//            }
//        }
    }
    //        // 发送本地推送，通知首页
    [CZNotificationCenter postNotificationName:kJPFNetworkDidReceiveMessageNotification object:userInfo];
    //下面的两个函数都可以用来播放音效文件，第一个函数伴随有震动效果
    //    AudioServicesPlayAlertSound(1007);
    //    // 发送本地推送，通知首页
    //    [CZNotificationCenter postNotificationName:kJPFNetworkDidReceiveMessageNotification object:userInfo];
    //
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    [[EaseMob sharedInstance] applicationDidEnterBackground:application];
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application{
    _locService = [[BMKLocationService alloc] init];
    // 定位
    [_locService startUserLocationService];
    // 先清空,避免重复创建
    _locService.delegate = nil;
    _locService.delegate = self;
    [self.timer invalidate];
    self.timer = nil;
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(timeToTrack) userInfo:nil repeats:YES];
    self.timer = timer;
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

#pragma mark ---上传会员经纬度
-(void)postMemberLocation {
       CZAccountModel *account = [CZMessageManager objectKeyedUnarchiverWithFileName:CZLOGISTICSACCOUNTFILENAME];
//    NSMutableDictionary *params1 = @{
//                             @"userId":[account.id stringValue],
//                             @"token":account.userToken,
//                             @"longitude":[NSString stringWithFormat:@"%lf",self.longitude],
//                             @"latitude":[NSString stringWithFormat:@"%lf",self.latitude]
//                             };
//    CZLog(@"%@",params1);
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:[account.id stringValue] forKey:@"userId"];
    [dict setObject:account.userToken forKey:  @"token"];
    [dict setObject:[NSString stringWithFormat:@"%lf",self.longitude] forKey:  @"longitude"];
    [dict setObject:[NSString stringWithFormat:@"%lf",self.latitude] forKey:   @"latitude"];

    NSDictionary * czparams = [NSDictionary dictionaryWithObject:dict forKey:@"czparams"];
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:czparams options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *str=[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    CZLog(@"%@",str);
//    [[CZNetWorkTool shareNetWorkTool]POST:@"http://192.168.16.217:8080/logistic/app/member/uploadAccountLocation.do" parameters:str success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        
//        CZLog(@"%@",responseObject);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//        
//        CZLog(@"%@",error);
//    }];
    [[CZNetWorkTool shareNetWorkTool]POST:@"http://192.168.16.217:8080/logistic/app/member/uploadAccountLocation.do" parameters:str progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        CZLog(@"%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        CZLog(@"%@",error);
    }];
    
}

#pragma mark - 每隔30秒定位，上传经纬度
- (void)timeToTrack{
    CZLog(@"----------------------------------");
    self.latitude = _locService.userLocation.location.coordinate.latitude;
    self.longitude = _locService.userLocation.location.coordinate.longitude;
//    CZLog(@"%lf---%lf",self.latitude, self.longitude);
    NSDictionary * dic = @{@"latitude":[NSString stringWithFormat:@"%lf",_locService.userLocation.location.coordinate.latitude],@"longitude":[NSString stringWithFormat:@"%lf",_locService.userLocation.location.coordinate.longitude]};
    //归档经纬度
    [CZMessageManager objectKeyArchiverWithObject:dic fileName:CZUSERLOCATIONFILENAME];
    // 发通知
    [CZNotificationCenter postNotificationName:CZLOCATIONNOTIFICATION object:dic];
    CZAccountModel *account = [CZMessageManager objectKeyedUnarchiverWithFileName:CZLOGISTICSACCOUNTFILENAME];
    if (account.userToken) {
        NSDictionary *params = @{
                                 @"userId"     :     [account.id stringValue],
                                 @"token"      :     account.userToken,
                                 @"longitude"  :     [NSString stringWithFormat:@"%lf",self.longitude],
                                 @"latitude"  :     [NSString stringWithFormat:@"%lf",self.latitude]
                                 };
        [CZNetwork postUploadLocationWithParams:params succsss:^(id json, id status) {
            
            if (status && [status isEqualToString:@"-3"]) {
                UIAlertController *vc = [UIAlertController alertControllerWithTitle:nil message:LOGINERRORMESSAGE preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *ac = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [vc addAction:ac];
                [self.window.rootViewController presentViewController:vc animated:YES completion:nil];
                return ;
            }
        } complete:^{
            
        } failure:^(NSError *error) {
            
        }];
    }
    //上传会员经纬度--新加
//    [self  postMemberLocation];
}



- (BOOL)needShowNotification:(NSString *)fromChatter
{
    BOOL ret = YES;
    NSArray *igGroupIds = [[EaseMob sharedInstance].chatManager ignoredGroupIds];
    for (NSString *str in igGroupIds) {
        if ([str isEqualToString:fromChatter]) {
            ret = NO;
            break;
        }
    }
    
    return ret;
}

// 环信收到消息回调
-(void)didReceiveMessage:(EMMessage *)message
{
    BOOL needShowNotification = (message.messageType != eMessageTypeChat) ? [self needShowNotification:message.conversationChatter] : YES;
    if (needShowNotification) {
#if !TARGET_IPHONE_SIMULATOR
        
        UIApplicationState state = [[UIApplication sharedApplication] applicationState];
        switch (state) {
            case UIApplicationStateActive:
                [self playSoundAndVibration];
                break;
            case UIApplicationStateInactive:
                [self playSoundAndVibration];
                break;
            case UIApplicationStateBackground:
                [self showNotificationWithMessage:message];
                break;
            default:
                break;
        }
#endif
    }
}

- (void)playSoundAndVibration{
    NSTimeInterval timeInterval = [[NSDate date]
                                   timeIntervalSinceDate:self.lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        //如果距离上次响铃和震动时间太短, 则跳过响铃
        CZLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
        return;
    }
    
    //保存最后一次响铃时间
    self.lastPlaySoundDate = [NSDate date];
    
    // 收到消息时，播放音频
    [[EMCDDeviceManager sharedInstance] playNewMessageSound];
    // 收到消息时，震动
    [[EMCDDeviceManager sharedInstance] playVibration];
    
    // 发送本地推送，通知首页
    
    [CZNotificationCenter postNotificationName:@"CZGETNOTIFICATION" object:@(YES)];
}

- (void)showNotificationWithMessage:(EMMessage *)message
{
    // 发送本地推送，通知首页
    [CZNotificationCenter postNotificationName:@"CZGETNOTIFICATION" object:@(YES)];
    EMPushNotificationOptions *options = [[EaseMob sharedInstance].chatManager pushNotificationOptions];
    //发送本地推送
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate date]; //触发通知的时间
    
    if (options.displayStyle == ePushNotificationDisplayStyle_messageSummary) {
        id<IEMMessageBody> messageBody = [message.messageBodies firstObject];
        NSString *messageStr = nil;
        switch (messageBody.messageBodyType) {
            case eMessageBodyType_Text:
            {
                messageStr = ((EMTextMessageBody *)messageBody).text;
            }
                break;
            case eMessageBodyType_Image:
            {
                messageStr = NSLocalizedString(@"message.image", @"Image");
            }
                break;
            case eMessageBodyType_Location:
            {
                messageStr = NSLocalizedString(@"message.location", @"Location");
            }
                break;
            case eMessageBodyType_Voice:
            {
                messageStr = NSLocalizedString(@"message.voice", @"Voice");
            }
                break;
            case eMessageBodyType_Video:{
                messageStr = NSLocalizedString(@"message.video", @"Video");
            }
                break;
            default:
                break;
        }
        
        //        NSString *title = [[UserProfileManager sharedInstance] getNickNameWithUsername:message.from];
        NSString *title = nil;
        if (message.messageType == eMessageTypeGroupChat) {
            NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
            for (EMGroup *group in groupArray) {
                if ([group.groupId isEqualToString:message.conversationChatter]) {
                    title = [NSString stringWithFormat:@"%@(%@)", message.groupSenderName, group.groupSubject];
                    break;
                }
            }
        }
        else if (message.messageType == eMessageTypeChatRoom)
        {
            NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
            NSString *key = [NSString stringWithFormat:@"OnceJoinedChatrooms_%@", [[[EaseMob sharedInstance].chatManager loginInfo] objectForKey:@"username" ]];
            NSMutableDictionary *chatrooms = [NSMutableDictionary dictionaryWithDictionary:[ud objectForKey:key]];
            NSString *chatroomName = [chatrooms objectForKey:message.conversationChatter];
            if (chatroomName)
            {
                title = [NSString stringWithFormat:@"%@(%@)", message.groupSenderName, chatroomName];
            }
        }
        
        notification.alertBody = [NSString stringWithFormat:@"%@:%@", title, messageStr];
    }
    else{
        notification.alertBody = NSLocalizedString(@"收到私聊消息", @"你有新的消息");
        //        notification.alertBody = [NSString stringWithFormat:@"%@:%@", title, messageStr];
    }
    
#warning 去掉注释会显示[本地]开头, 方便在开发中区分是否为本地推送
    //notification.alertBody = [[NSString alloc] initWithFormat:@"[本地]%@", notification.alertBody];
    
    notification.alertAction = NSLocalizedString(@"open", @"Open");
    notification.timeZone = [NSTimeZone defaultTimeZone];
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:self.lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        CZLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
    } else {
        notification.soundName = UILocalNotificationDefaultSoundName;
        self.lastPlaySoundDate = [NSDate date];
    }
    
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
    [userInfo setObject:[NSNumber numberWithInt:message.messageType] forKey:kMessageType];
    [userInfo setObject:message.conversationChatter forKey:kConversationChatter];
    notification.userInfo = userInfo;
    
    //发送通知
    //        // 发送本地推送，通知首页
    [CZNotificationCenter postNotificationName:CZIMMESSAGENOTIFICATION object:userInfo];
    
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    
    UIApplication *application = [UIApplication sharedApplication];
    application.applicationIconBadgeNumber += 1;
}



- (void)networkDidReceiveMessage:(NSNotification *)notification {
//    AudioServicesPlayAlertSound(1007);
}

// 监听系统生命周期回调，以便将需要的事件传给SDK
- (void)setupNotifiers{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidEnterBackgroundNotif:)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appWillEnterForeground:)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidFinishLaunching:)
                                                 name:UIApplicationDidFinishLaunchingNotification
                                               object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidBecomeActiveNotif:)
                                                 name:UIApplicationDidBecomeActiveNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appWillResignActiveNotif:)
                                                 name:UIApplicationWillResignActiveNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidReceiveMemoryWarning:)
                                                 name:UIApplicationDidReceiveMemoryWarningNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appWillTerminateNotif:)
                                                 name:UIApplicationWillTerminateNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appProtectedDataWillBecomeUnavailableNotif:)
                                                 name:UIApplicationProtectedDataWillBecomeUnavailable
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appProtectedDataDidBecomeAvailableNotif:)
                                                 name:UIApplicationProtectedDataDidBecomeAvailable
                                               object:nil];
}



#pragma mark - notifiers
- (void)appDidEnterBackgroundNotif:(NSNotification*)notif{
    [[EaseMob sharedInstance] applicationDidEnterBackground:notif.object];
    
}





- (void)appWillEnterForeground:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationWillEnterForeground:notif.object];
}

- (void)appDidFinishLaunching:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationDidFinishLaunching:notif.object];
}

- (void)appDidBecomeActiveNotif:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationDidBecomeActive:notif.object];
}

- (void)appWillResignActiveNotif:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationWillResignActive:notif.object];
}

- (void)appDidReceiveMemoryWarning:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationDidReceiveMemoryWarning:notif.object];
}

- (void)appWillTerminateNotif:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationWillTerminate:notif.object];
}

- (void)appProtectedDataWillBecomeUnavailableNotif:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationProtectedDataWillBecomeUnavailable:notif.object];
}

- (void)appProtectedDataDidBecomeAvailableNotif:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationProtectedDataDidBecomeAvailable:notif.object];
}



@end
